package com.chushouya.manager.dao.repository;

import com.chushouya.manager.dao.entity.RoleEntity;
import com.chushouya.manager.dao.mapper.RoleEntityMapper;
import com.chushouya.manager.dto.admin.role.RoleQuery;
import com.general.framework.core.enums.DelFlagEnum;
import com.general.framework.core.enums.StatusEnum;
import com.general.framework.core.lang.Lists;
import com.general.framework.core.lang.Strings;
import com.general.framework.core.schema.PageResult;
import com.general.framework.data.mybatis.BaseRepository;
import org.springframework.stereotype.Repository;
import tk.mybatis.mapper.entity.Example;

import java.util.List;
import java.util.Objects;

@Repository
public class RoleRepository extends BaseRepository<RoleEntityMapper, RoleEntity, Long> {

    public PageResult<RoleEntity> selectRolePageResult(RoleQuery query) {
        return this.selectPage(query.getPageRequest(), this.buildExample(query));
    }

    public List<RoleEntity> selectRoleList(RoleQuery query) {
        Example example = buildExample(query);
        return this.selectByExample(example);
    }

    private Example buildExample(RoleQuery query) {
        Example example = this.buildExample();
        if (Strings.isNotEmpty(query.getRoleName())) {
            example.and().andLike("roleName", Strings.format("%{}%", query.getRoleName()));
        }
        if (Objects.nonNull(query.getStatus())) {
            example.and().andEqualTo("status", query.getStatus());
        }
        if (Strings.isNotEmpty(query.getRoleKey())) {
            example.and().andEqualTo("roleKey", query.getRoleKey());
        }
        if (Lists.isNotEmpty(query.getRoleKeyList())) {
            example.and().andIn("roleKey", query.getRoleKeyList());
        }
        example.and().andEqualTo("delFlag", DelFlagEnum.normal.getValue());
        return example;
    }

    public List<RoleEntity> selectByRoleIdList(List<Long> roleIdList) {
        Example example = this.buildExample();
        example.and().andIn("roleId", roleIdList)
                .andEqualTo("status", StatusEnum.normal.value())
                .andEqualTo("delFlag", DelFlagEnum.normal.getValue());
        return this.selectByExample(example);
    }

    public RoleEntity selectOneRole(RoleQuery query) {
        Example example = this.buildExample();
        if (Strings.isNotEmpty(query.getRoleName())) {
            example.and().andEqualTo("roleName", query.getRoleName());
        }
        if (Objects.nonNull(query.getRoleKey())) {
            example.and().andEqualTo("roleKey", query.getRoleKey());
        }
        if (Objects.nonNull(query.getIdNotEqualTo())) {
            example.and().andNotEqualTo("roleId", query.getIdNotEqualTo());
        }
        return this.selectFirstOneByExample(example);
    }
}
